package com.bookstore.servlet.client;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;
import com.bookstore.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/client/user.do")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    //1.登录 ?action=login
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        User login = userService.login(user);
        if (login != null) {
            //登录成功
            response.sendRedirect(request.getContextPath() + "/index.html");
        }else {
            //登录失败
            response.sendRedirect("./login.html");
        }
    }

    //2.注册  ?action=register
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        String introduce = request.getParameter("introduce");
        User user = new User(null, username, password, gender, email, telephone, introduce, null, 1, 0, new Date());
        int result = userService.register(user);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (result > 0) {
            writer.write("<h1>用户注册成功！</h1>");
        } else {
            writer.write("<h1>用户注册失败！</h1>");
        }
    }
}
